package com.ls.controller.interceptor;

import com.ls.entity.User;
import com.ls.service.DataService;
import com.ls.util.UserContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ls
 * @version v1.0
 * @description 数据统计拦截器
 * @date 2021/8/24 0:22
 */
@Component
public class DataInterceptor implements HandlerInterceptor {

    @Autowired
    private DataService dataService;

    @Autowired
    private UserContextHolder userContextHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 记录独立访客 uv
        String ip = request.getRemoteHost();
        dataService.recodeUv(ip);

        //记录活跃用户 dau
        User user = userContextHolder.getUser();
        if (user != null) {
            dataService.recodeDau(user.getId());
        }
        return true;
    }
}
